package com.zkq.graduate.util;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author zhangkaiqiang
 * @Date 2019/10/28  9:52
 * @Description TODO
 */
public class MongoDBUtil {



	private static String databaseName="test";
	private static String collectionName="graduate";

	/**
	 * 默认不指定参数创建到mongodb的连接
	 * @return
	 */
	public static MongoCollection<Document> getConnection(MongoClient mongoClient){
		MongoDatabase database = mongoClient.getDatabase(databaseName);
		return database.getCollection(collectionName);
	}


	/***
	 * @Author zhangkaiqiang
	 * @Description TODO
	 * @Date 10:10 2019/10/28 
	 * @param
	 * @param databaseName
	 * @param collectionName
	 * @return com.mongodb.client.MongoCollection<org.bson.Document>
	 **/
	public static MongoCollection<Document> getConnection(MongoClient mongoClient,String databaseName,String collectionName){
		MongoDatabase database = mongoClient.getDatabase(databaseName);
		return database.getCollection(collectionName);
	}


	/**
	 * 向集合中插入一个文档
	 * @param map
	 * @param collection
	 */
	public void insertOneDocument(Map<String,Object> map,MongoCollection<Document> collection){
		if(map!=null&&!map.isEmpty()&&collection!=null){
			Document document = new Document();
			map.forEach((key,value)->{
				document.append(key,value);
			});
			collection.insertOne(document);
		}
	}

	/**
	 * 一次性向collection中插入多个文档
	 * @param listMap
	 * @param collection
	 */
	public void insertManyDocument(List<Map<String,Object>> listMap,MongoCollection<Document> collection){
		if(listMap!=null&&listMap.size()>0&&collection!=null){
			List<Document> list=new ArrayList<>();

			listMap.forEach((item)->{
				Document document=new Document();
				item.forEach((key,value)->{
					document.append(key,value);
				});
				list.add(document);
			});
			collection.insertMany(list);
		}
	}


	/**
	 * 得到某个collection中的所有文档
	 * @param collection
	 * @return
	 */
	public static FindIterable<Document> getAll(MongoCollection<Document> collection){
		if(collection!=null){
			return collection.find();
		}
		return null;
	}


	/**
	 * 根据条件查找某个collection中的某些文档
	 * @param collection
	 * @param condition
	 * @return
	 */
	public static FindIterable<Document> getByAddition(MongoCollection<Document> collection,Map<String,Object> condition){
		if(collection!=null&&condition!=null){
			Document document=new Document();
			condition.forEach((key,value)->{
				document.append(key,value);
			});
			return collection.find(document);
		}
		return null;
	}




}
